package com.lubase.metadata.service;

import com.lubase.core.extend.LoadSubTableDataService;
import com.lubase.orm.QueryOption;
import com.lubase.orm.TableFilter;
import com.lubase.model.DbCollection;
import com.lubase.orm.service.DataAccess;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MtTableLoadSubTableDataService implements LoadSubTableDataService {
    @Override
    public String getId() {
        return "1477030576308359168";
    }

    @Override
    public String getParentTableId() {
        return "1472601080805199872";
    }

    @Override
    public String getDescription() {
        return "获取表的关联关系";
    }

    @Autowired
    DataAccess dataAccess;

    @Override
    public DbCollection loadChildTableData(String dataId) {
        if (StringUtils.isEmpty(dataId)) {
            return null;
        }
        QueryOption queryOption = new QueryOption("mt_table");
        queryOption.setFixField("table_code");
        queryOption.setTableFilter(new TableFilter("id", dataId));
        DbCollection collection = dataAccess.queryAllData(queryOption);
        if (collection.getData().isEmpty()) {
            return null;
        }
        String tableCode = collection.getData().get(0).get("table_code").toString();
        if (StringUtils.isNotEmpty(tableCode)) {
            queryOption = new QueryOption("mt_constraint");
            queryOption.setFixField("column_code,ref_table_code,ref_column_code,from_database,constraint_name");
            queryOption.setTableFilter(new TableFilter("table_code", tableCode));
            queryOption.setSortField("from_database");
            return dataAccess.queryAllData(queryOption);
        }
        return null;
    }

    @Override
    public String getChildTableCode() {
        return "mt_constraint";
    }
}

